# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import SipUser
from .ConnFreeswitch import *
from .MySqlite import *
from .Licence import *
from .filePath import *

class SipUserAdmin(object):
    show_terminal = True
    list_display = ['dn', 'callgroup']
    model_icon="fa fa-phone'"
    search_fields = ['dn','callgroup']
    ordering = ["dn"]
    add_form_template = 'SipUser.html'
    change_form_template = 'SipUserEdit.html'

    # 每页显示多少个
    list_per_page = 10

    #隐藏删除
    #def has_delete_permission(self):
    #    return False

    def delete_models(self, obj):
        #strDn = str(obj).replace("<SipUser: ","").replace("[","").replace("]","").replace(">","").replace(" ","").split(',')
        #print strDn
        r = deleteXml(obj)
        if r == -1:
            self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')
        elif r == -2:
            self.message_user(u'告警,号码删除XML失败，请手动删除XML!', 'warning')
        else:
            self.message_user(u'恭喜,删除成功', 'success')
        obj.delete()

    def valid_forms(self):

           #self.message_user(u'告警,', 'warning')
        #self.message_user(u'恭喜,', 'success')
        #self.message_user(u'信息,', 'info')
        ls = LicensesSum(ReadFile(getcwd()+"/sipnumlicenses.jx"))
        if ls == 0:
            self.message_user(u'未找到SIP用户许可，注册码：'+getLicenses(), 'error')
        else:
            srterror = str(self.get_error_list())
            if srterror == '':
                data = str(self.form_obj.data)
                if data.find("u'_save'") > -1:
                    dn = int(self.form_obj.data["dn"])
                    num = int(self.form_obj.data["number"])
                    strsql = "select count(*) from pbx_sipuser where dn=" + str(dn)
                    sipnum = ReadSql("select count(*) from pbx_sipuser")[0][0]
                    if int(sipnum)+num > int(ls) :
                        self.message_user(u'错误,已超过SIP用户许可，SIP用户许可剩余：'+str(int(ls)-int(sipnum))+' 总数：'+str(ls), 'error')
                    else:
                        if num > 1:
                            strsql = "select count(*) from pbx_sipuser where dn>=" + str(dn) + " and dn<=" + str(
                                dn + num - 1);
                        data = str(self.form_obj.data)
                        if str(ReadSql(strsql)) == "((0,),)":
                            return self.form_obj.is_valid()
                        else:
                            self.message_user(u'错误,已存在已有号码', 'error')
                else:
                    # self.message_user(u'信息,', 'info')
                    return self.form_obj.is_valid()

    def save_models(self):
        obj = self.new_obj
        num = obj.number
        dn = obj.dn
        password = obj.password
        if obj.vm_password == "":
            vm_password = str(dn)
        else:
            vm_password = obj.vm_password
        if obj.accountcode == "":
            accountcode = str(dn)
        else:
            accountcode = obj.accountcode
        if obj.effective_caller_id_name == "":
            effective_caller_id_name = str(dn)
        else:
            effective_caller_id_name = obj.effective_caller_id_name
        if obj.effective_caller_id_number == "":
            effective_caller_id_number = str(dn)
        else:
            effective_caller_id_number = obj.effective_caller_id_number
        outbound_caller_id_name = obj.outbound_caller_id_name
        outbound_caller_id_number = obj.outbound_caller_id_number
        callgroup = obj.callgroup
        TIMEOUT = obj.TIMEOUT
        failnum = obj.failnum
        # request = self.request
        # obj.author = str(request.user)
        if (str(self.form_obj.data).find('toll_allow') == -1):  # 查找是否选择了权限
            toll_allow = ''
        else:
            strID = str(self.form_obj.data)[str(self.form_obj.data).index('toll_allow'):].replace("toll_allow': [", "") \
                .replace("]}>", "").replace("u", "")
            toll_allow = strID.replace(" ","").replace("'","")
        if (str(self.form_obj.data).find('onfail') == -1):  # 查找是否选择了权限
            onfail = ''
        else:
            onfail = str(self.form_obj.data)[str(self.form_obj.data).index('onfail'):].split("]")[0].replace("onfail': [", "").replace("u'", "").replace(" ","").replace("'","")
        r = save(obj,toll_allow)
        obj.toll_allow = toll_allow
        obj.onfail=onfail

        if r == -1:
            self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')
        if r == -2:
            self.message_user(u'告警,号码写入XML失败，请手动添加/修改XML!', 'warning')

        if num == 0:
            self.new_obj.save()
        elif num == 1:
            SipUser_list_to_insert = list()
            for x in range(num):
                SipUser_list_to_insert.append(SipUser(
                    dn=dn + x, number=1, password=password, vm_password=vm_password
                    , toll_allow=toll_allow
                    , accountcode=accountcode
                    , effective_caller_id_name=effective_caller_id_name
                    , effective_caller_id_number=effective_caller_id_number
                    , outbound_caller_id_name=outbound_caller_id_name
                    , outbound_caller_id_number=outbound_caller_id_number
                    , callgroup=callgroup
                    , TIMEOUT=TIMEOUT
                    , onfail=onfail
                    , failnum=failnum
                ))
            SipUser.objects.bulk_create(SipUser_list_to_insert)
        else:
            SipUser_list_to_insert = list()
            for x in range(num):
                SipUser_list_to_insert.append(SipUser(
                    dn=dn + x, number=1, password=password, vm_password=dn + x
                    ,toll_allow=toll_allow
                    , accountcode=dn + x
                    , effective_caller_id_name=dn + x
                    , effective_caller_id_number=dn + x
                    , outbound_caller_id_name=outbound_caller_id_name
                    , outbound_caller_id_number=outbound_caller_id_number
                    , callgroup=callgroup
                    , TIMEOUT=TIMEOUT
                    , onfail=onfail
                    , failnum=failnum
                ))
            SipUser.objects.bulk_create(SipUser_list_to_insert)


def save(obj,toll_allow):
    num = obj.number
    dn = obj.dn
    password = obj.password
    if obj.vm_password == "":
        vm_password = str(dn)
    else:
        vm_password = obj.vm_password
    if obj.accountcode == "":
        accountcode = str(dn)
    else:
        accountcode = obj.accountcode
    user_context = obj.user_context
    if obj.effective_caller_id_name == "":
        effective_caller_id_name = str(dn)
    else:
        effective_caller_id_name = obj.effective_caller_id_name
    if obj.effective_caller_id_number == "":
        effective_caller_id_number = str(dn)
    else:
        effective_caller_id_number = obj.effective_caller_id_number
    outbound_caller_id_name = obj.outbound_caller_id_name
    outbound_caller_id_number = obj.outbound_caller_id_number
    callgroup = obj.callgroup
    try:
        info =ReadFile(push_file_path())
        if num <= 1:
            info = info.replace("{id}", str(dn)).replace("{password}", password).replace("{vm-password}",vm_password)
            info = info.replace("{accountcode}",accountcode).replace("{toll_allow}",toll_allow).replace("{effective_caller_id_name}",effective_caller_id_name)
            info = info.replace("{effective_caller_id_number}",effective_caller_id_number).replace("{outbound_caller_id_name}",outbound_caller_id_name)
            info = info.replace("{outbound_caller_id_number}",outbound_caller_id_number).replace("{callgroup}",callgroup).replace("{user_context}",user_context)
            WriteFile(w_file_path()+str(dn)+".xml",info)
        else:
            for x in range(num):
                ddn  = str(dn+x)
                pinfo = info
                pinfo = pinfo.replace("{id}", ddn).replace("{password}", password).replace("{vm-password}",ddn)
                pinfo = pinfo.replace("{accountcode}", ddn).replace("{toll_allow}", toll_allow).replace("{effective_caller_id_name}", ddn)
                pinfo = pinfo.replace("{effective_caller_id_number}", ddn).replace("{outbound_caller_id_name}", outbound_caller_id_name)
                pinfo = pinfo.replace("{outbound_caller_id_number}", outbound_caller_id_number).replace("{callgroup}",callgroup).replace("{user_context}",user_context)
                WriteFile(w_file_path() + ddn + ".xml", pinfo)
        return ReloadXml()
    except Exception as e:
        print e
        return -2

def deleteXml(strDn):
    i =0
    try:
        for vars in strDn:
            path=w_file_path()+str(vars)+".xml"
            print path
            if os.path.exists(path):
                os.remove(path)
            else:
                i=1
                print '文件不存在:'+path  # 则返回文件不存在
        r = ReloadXml()
        if i==1:
            return -2
        else:
            return r
    except Exception as e:
        print e
        return -2